<template>
  <bc-container>
    <div class="parking-box">
      <div style="width: 350px">
        <data-panel
          ref="dataPanelRef"
          :tableAttrs="tableAttrs"
          :columns="columns"
          :dataSource="tableData"
          :otherQuery="otherQuery"
          @radio-change="radioChange"
          paginationLayout="total, prev, pager, next,"
        >
          <template #toolbar>
            <el-button type="primary" @click="handleAdd">新增车位</el-button>
            <el-button type="primary" @click="handleImport">导入</el-button>
            <el-select
              v-model="otherQuery.garageId"
              placeholder="楼层"
              style="margin-left: 12px; width: 240px"
              clearable
            >
              <el-option v-for="item in floorList" :key="item.id" :label="item.floorName" :value="item.id" />
            </el-select>
          </template>
        </data-panel>
      </div>
      <div class="map-box">
        <div class="img-box">
          <canvas-map
            ref="canvasMapRef"
            v-if="garageMap"
            :mapUrl="garageMap"
            :points="drawPoints"
            @draw-complete="toggleDrawMode"
          ></canvas-map>
        </div>

        <div class="data-panel" v-if="parkingInfo && Object.keys(parkingInfo).length > 0">
          <div class="data-panel-header">
            <div class="data-panel-cell">
              <div class="cell-title">楼层</div>
              <div>{{ parkingInfo.garageName }}</div>
            </div>
            <div class="data-panel-cell">
              <div class="cell-title">车库类型</div>
              <div>{{ parkingInfo.garageTypeName }}</div>
            </div>
            <div class="data-panel-cell">
              <div class="cell-title">车位号</div>
              <div>{{ parkingInfo.spaceNum }}</div>
            </div>
            <div class="data-panel-cell">
              <div class="cell-title">车位售价</div>
              <div>{{ parkingInfo.price }}</div>
            </div>
            <div class="data-panel-cell">
              <div class="cell-title">车位状态</div>
              <div>{{ parkingInfo.statusName }}</div>
            </div>
            <div class="data-panel-cell">
              <div class="cell-title">车位类型</div>
              <div>{{ parkingInfo.typeName }}</div>
            </div>
            <div class="data-panel-cell">
              <div class="cell-title">是否锁定</div>
              <div>{{ parkingInfo.isLocked == 1 ? '已锁定' : '未锁定' }}</div>
            </div>
            <div class="data-panel-cell">
              <div class="cell-title">操作</div>
              <div>
                <el-button type="primary" link @click="handleEditOrDetail('detail')">详情</el-button>
                <el-button type="primary" link @click="handleEditOrDetail('edit')">编辑</el-button>
                <el-button type="primary" link @click="handleJump">浏览记录</el-button>
                <el-button type="primary" link @click="handleDel">删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </bc-container>
  <bc-modal size="650" type="drawer" :title="formTitle()" v-model="dialogVisible" footer>
    <el-form ref="ruleFormRef" label-position="right" :model="formData" label-width="auto">
      <bc-form ref="bcFormRef" :border="false" :fields="formOptions" :cols="2" :mode="mode" @change="handleChange">
      </bc-form>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </bc-modal>
  <!-- 导入弹窗 -->
  <import-dialog ref="importDialogRef" @change="loadData" />
</template>

<script setup>
import { reactive, shallowRef, onMounted, ref, watch, nextTick } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import DataPanel from '@/components/DataPanel.vue'
import BcModal from '@/components/BcModal.vue'
import BcForm from '@/components/bcForm/Index.vue'
import ImportDialog from './ImportDialog.vue'
import { useRouter } from 'vue-router'
const router = useRouter()
import { formOptions } from './config'
import CanvasMap from './CanvasMap.vue'

// Store
const userStore = useUserStore()

// 状态定义
const parkingInfo = reactive({})
const dataPanelRef = shallowRef()
const garageMap = ref(null)
const mode = ref('edit')
const ruleFormRef = ref()
const bcFormRef = ref()
const dialogVisible = ref(false)
const formData = reactive({})

// 获取车库地图组件引用
const canvasMapRef = shallowRef()
const drawPoints = ref([])

// 表格配置
const otherQuery = reactive({ communityId: userStore.communityId, garageId: null })
const tableAttrs = { radio: true }
const columns = [
  { label: '车位号', prop: 'spaceNum' },
  {
    label: '车位类型',
    prop: 'type',
    type: 'select',
    width: '80px',
    options: [
      { label: '子母车位', value: 1 },
      { label: '无障碍车位', value: 2 },
      { label: '标准车位', value: 3 },
      { label: '非标准车位', value: 4 },
      { label: '大车位', value: 5 },
    ],
  },
  {
    label: '状态',
    prop: 'status',
    type: 'select',
    width: '50px',
    options: [
      { label: '禁用', value: 0 },
      { label: '空闲', value: 1 },
      { label: '已售', value: 2 },
      { label: '已租', value: 3 },
    ],
  },
]

// 数据加载方法
const tableData = async (params, other) => {
  params = { ...params, ...other }
  const res = await $request.post('/api-parking/space/list', { params })
  return {
    rows: (res?.rows || []).map((i) => {
      const imageUrl = i.imageUrl ? [{ url: i.imageUrl }] : null
      return { ...i, imageUrl }
    }),
    total: res.total ?? 0,
  }
}

const loadData = () => {
  nextTick(() => dataPanelRef.value.load())
}

const getGarageMap = async (row) => {
  try {
    const res = await $request.get('/api-parking/parking/garage/queryGarageById', {
      params: { id: row.garageId },
    })
    garageMap.value = res.structureUrl
  } catch (error) {
    console.error('获取车库地图失败:', error)
  }
}

const getDefaultGarageMap = async () => {
  try {
    const params = { communityId: userStore.communityId, pageSize: 1, pageNum: 1 }
    const res = await $request.post('/api-parking/space/list', { params })
    if (res.rows && res.rows.length > 0) {
      const firstRow = res.rows[0]
      if (firstRow.garageId) {
        await getGarageMap(firstRow)
      }
    }
  } catch (error) {
    console.error('获取默认车库地图失败:', error)
  }
}

const toggleDrawMode = (rect) => {
  if (rect) {
    const params = { id: parkingInfo.id, coordinates: JSON.stringify(rect) }
    $request
      .post('/api-parking/space/update', { params })
      .then(() => {
        ElMessage({ type: 'success', message: '绘制区域已保存' })
        parkingInfo.coordinates = JSON.stringify(rect)
        drawPoints.value = [rect]
        loadData()
      })
      .catch((error) => {
        ElMessage({ type: 'error', message: `保存失败: ${error.message}` })
      })
  }
}

// 表单方法
const formTitle = () => {
  const modeMap = { add: '新增', edit: '编辑' }
  if (mode.value === 'detail') return '车位详情'
  return `${modeMap[mode.value] || ''}车位`
}

const handleChange = (val) => {
  Object.assign(formData, val.value)
}

const onClose = () => {
  dialogVisible.value = false
}

const onOpen = (val) => {
  dialogVisible.value = true
  Object.keys(formData).forEach((key) => delete formData[key])
  Object.assign(formData, val)
  nextTick(() => {
    bcFormRef.value.set(val)
    ruleFormRef.value.resetFields()
  })
}

const handleAdd = () => {
  mode.value = 'add'
  onOpen({ communityId: userStore.communityId, isTemporary: 0, isNewEnergy: 0 })
}
// 编辑
const handleEditOrDetail = async (val) => {
  const info = { ...parkingInfo }
  mode.value = val
  onOpen(info)
}

const handleSubmit = async () => {
  try {
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        const params = { ...formData }
        params['imageUrl'] = params?.imageUrl?.[0].url
        await $request.post(mode.value === 'add' ? '/api-parking/space/add' : '/api-parking/space/update', { params })
        Object.assign(parkingInfo, params)
        onClose()
        ElMessage({ type: 'success', message: '操作成功' })
        loadData()
      }
      return false
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

// 跳转到浏览记录
const handleJump = () => {
  if (!parkingInfo.id) {
    ElMessage({ type: 'warning', message: '请先选择一个车位' })
    return
  }
  router.push(`/parking-share/${parkingInfo.id}`)
}

// ============== 导入相关 ==============
const importDialogRef = ref(null)
const handleImport = async () => {
  await nextTick()
  console.log('导入车位数据', userStore.communityId, otherQuery.garageId)
  importDialogRef.value.open(userStore.communityId, otherQuery.garageId)
}

//  ---- 删除 ----
const handleDel = () => {
  const { id } = parkingInfo
  ElMessageBox.confirm(`是否删除该车位?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 执行删除操作
      await $request.get('/api-parking/space/remove', { params: { id: id } })
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      // 刷新表单
      loadData()
    })
    .catch(() => {
      // 显示取消消息
    })
}

const radioChange = (row) => {
  getGarageMap(row)
  Object.assign(parkingInfo, row)

  if (parkingInfo.coordinates) {
    const coordinates = JSON.parse(parkingInfo.coordinates)
    drawPoints.value = [coordinates]

    canvasMapRef.value.centerAt(coordinates.x + coordinates.width / 2, coordinates.y + coordinates.height / 2)
  } else {
    drawPoints.value = []
  }
}

const floorList = ref([])
const getFloorList = async () => {
  try {
    const params = {
      pageSize: 999,
      pageNum: 1,
      communityId: userStore.communityId,
    }
    const res = await $request.post('/api-parking/parking/garage/QueryGarage', { params })
    floorList.value = res?.rows || []
    if (floorList.value.length) {
      otherQuery.garageId = floorList.value[0].id
    }
  } catch (error) {
    floorList.value = []
  }
}

// 监听器
watch(
  () => userStore.communityId,
  () => {
    otherQuery.communityId = userStore.communityId
    if (userStore.communityId) {
      getDefaultGarageMap()
      loadData()
      getFloorList()
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.parking-box {
  width: 100%;
  height: 100%;
  display: flex;
  gap: 16px;
}
.map-box {
  position: relative;
  height: 100%;
  flex: 1;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  .data-panel {
    position: relative;
    width: 100%;
    height: 70px;
    .data-panel-header {
      width: 100%;
      display: flex;
      justify-content: center;
    }
    .data-panel-cell {
      text-align: center;
      border: 1px solid #e4e7ed;
      margin-left: -1px;
      flex-shrink: 0;
      div {
        padding: 5px;
      }
      .cell-title {
        border-bottom: #e4e7ed 1px solid;
      }
    }
  }
  .img-box {
    position: relative;
    overflow: hidden;
    height: calc(100% - 70px);
    width: 100%;
    canvas {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
